import router, { asyncRoutes } from './router'
// 导入进度条插件
import NProgress from 'nprogress'
// 导入进度条样式
import 'nprogress/nprogress.css'
import store from '@/store'
import getPageTitle from '@/utils/get-page-title.js'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

// 路由白名单
const whiteList = ['/login', '/404']
// 全局路由前置守卫
// eslint-disable-next-line
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const token = store.getters.token
  // 登录了
  if (token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      // 如果手动让cookie里token改错误，刷新以后，vuex才会从本地取出错误token
      // 刷新时，路由守卫会从/跳转到地址栏里路由地址，所以先让页面跳转进去
      // 执行下面请求会401，被动退出时，才能拿到跳转后的路由地址(未遂地址给登录页面，否则next在下面，未遂地址一直是 /
      next()
      if (!store.getters.name) {
        // await等待执行完毕有了userInfo再执行后面代码拿取userInfo.roles.menus
        await store.dispatch('user/getProfile')
        const filterRoutes = asyncRoutes.filter((routeObj) => {
          const routeName = routeObj.children[0].name.toLowerCase()
          const userMenus = store.state.user.userInfo.roles.menus
          return userMenus.includes(routeName)
        })
        filterRoutes.push({ path: '*', redirect: '/404', hidden: true })
        router.addRoutes(filterRoutes)
        store.commit('permissions/setRoutes', filterRoutes)
        next({
          path: to.path,
          replace: true
        })
      }
    }
  } else {
    // 没有登录
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

// 全局路由后置守卫
router.afterEach((to, from) => {
  document.title = getPageTitle(to.meta.title)
  // 正常next()放行了跳转了，才会走后置守卫，关闭正常流程进度条
  NProgress.done()
})
